#pragma once
#include <graphics.h>
#include <vector>
#include <string>
#include "TableWidget.h"
#include <algorithm>
#define PLOTVIEW_H

#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))

class PlotView {
public:
    // 构造函数
    PlotView();
    PlotView(int panelWidth, int screenWidth, int screenHeight);

    // 坐标转换
    int toScreenX(double worldX) const;
    int toScreenY(double worldY) const;
    double toWorldX(int screenX) const;
    double toWorldY(int screenY) const;

    // 视图控制
    void setViewCenter(double x, double y);
    void getViewCenter(double& x, double& y) const;
    void setZoom(double zoom);
    double getZoom() const;
    void resetView(double x = 0, double y = 0, double zoom = 1.0);

    // 绘制功能
    void drawPoint(double x, double y, COLORREF color, int size = 3) const;
    void drawLine(double x1, double y1, double x2, double y2, COLORREF color, int thickness = 1) const;
    void drawCoordinateSystem() const;


    void mouseWheel(int mouseX, int mouseY, int wheel);
    void mouseClick(int mouseX, int mouseY);
    void mouseMove(int mouseX, int mouseY);
    void ButtonUp(int mouseX, int mouseY);
    //void ButtonDblClk(int mouseX, int mouseY);
    // 输入处理
    void handleInput();

    // 数据管理
    struct DataPoint {
        double x, y;
        std::wstring label;
        COLORREF color;
        int size;
    };

    struct LineSegment {
        double x1, y1, x2, y2;
        COLORREF color;
        int thickness;
    };

    void addDataPoint(double x, double y, const std::wstring& label, COLORREF color = RGB(255, 0, 0), int size = 3);
    void addLineSegment(double x1, double y1, double x2, double y2, COLORREF color = RGB(0, 255, 0), int thickness = 1);
    void clearAllData();
    void drawAllData() const;
    int Getm_panelWidth();
private:
    // 视图状态
    struct ViewState {
        double centerX = 0;
        double centerY = 0;
        double zoom = 1.0;
        bool isDragging = false;
        int lastMouseX = 0, lastMouseY = 0;
    } m_viewState;

    // 布局参数
    int m_panelWidth;
    int m_screenWidth;
    int m_screenHeight;
    int m_plotWidth;



    // 数据存储
    std::vector<DataPoint> m_dataPoints;
    std::vector<LineSegment> m_lineSegments;

    // 辅助函数
    void drawGridLines(double interval, bool isXAxis) const;
    void drawAxis() const;
    void drawTicks(double interval, bool isXAxis) const;
    void drawAxisLabels() const;
    double calculateTickInterval(double range) const;
    void drawSingleTick(double value, bool isXAxis) const;
};

// PLOTVIEW_H